package org.goldenport.g3.adapters

import scala.xml.{XML, Elem}
import java.io._
import java.net.{URL, URI}
import org.goldenport.g3._
import org.goldenport.g3.messages._
import org.goldenport.g3.events._

/**
 * @since   Sep. 23, 2010
 * @version Oct. 10, 2010
 * @author  ASAMI, Tomoharu
 */
class HtmlAdapter(val html: Html) extends G3Adapter with ActivityActionable {
  val driver = new HtmlDriver(html)

  def create_Activity(ctx: G3AgentContext) = driver.createDriverActivity(ctx)
}

class HtmlDriver(val html: Html) extends G3Driver {
  override protected def driver_Activity(ctx: G3AgentContext): PartialFunction[AnyRef, AnyRef] = {
/*
    case get: Get => execute(get, ctx)
    case post: Post => execute(post, ctx)
    case put: Put => execute(put, ctx)
    case delete: Delete => execute(delete, ctx)
*/
    case get: Get => error("Get")
    case post: Post => error("Post")
    case put: Put => error("Put")
    case delete: Delete => error("Delete")
    case Nil => execute(Get(""), ctx)
    case uris: List[String] => execute(Get(uris(0)), ctx)
    case cmd: Ping => execute(Get(""), ctx)
    case cmd: G3Command => execute(Get(cmd.uri), ctx)
    case r: Record => execute(Get("", Some(r)), ctx)
    case rs: RecordSet => execute(Get("", Some(rs)), ctx)
  }

  protected def new_Agent(cmd: G3Command, ctx: G3AgentContext): HtmlDriverAgent = {
    new HtmlDriverAgent(html, ctx)
  }
}

class HtmlDriverAgent(html: Html, context: G3AgentContext) extends G3DriverAgent("", context) {
  private def make_html(cmd: RestCommand): Html = {
    val part = cmd.content match {
      case Some(r: Record) => html += r
      case Some(rs: RecordSet) => html += rs
      case Some(s: String) => html += s
      case None => html
    }
    context.masterHtml.inject(part, context)
  }

  def get(get: Get): G3Event = {
    Getted(get.uri, make_html(get))
  }

  def post(post: Post): G3Event = {
    Posted(post.uri, make_html(post))
  }

  def put(put: Put): G3Event = {
    Putted(put.uri, make_html(put))
  }

  def delete(delete: Delete): G3Event = {
    Deleted(delete.uri, make_html(delete))
  }

  def mkcol(mkcol: Mkcol): G3Event = {
    error("XXX mkcol")
  }
}
